<?php
namespace app\controller;

use app\BaseController;
use app\model\Carouse;
use app\model\Category as CategoryModel;
use app\model\ChooseGoods;
use app\model\GoodsAuthor;
use app\model\UserCollection;
use app\model\WisemanGoods;
use app\traits\CommonTrait;
use app\model\ActivityGoods;
use think\facade\Db;

class Goods extends BaseController
{
    use CommonTrait;

    /**
     * 获取所有分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function category(){
        $categories = CategoryModel::field('cate_name,cid')->where('pid',0)->select();
        return $this->apiJson(1, 'ok', $categories);
    }


    /**
     * 商品列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(){
        $cid = request()->param('cid', 0);
        $name = request()->param('name', '');
        $type = request()->param('type', 0);
        $id = request()->param('id', '');
        $share = request()->param('share', 0);
        $currentPage = request()->param('current_page', 1);
        $pageSize = request()->param('per_page', 10);
        $perPage = $pageSize > 100 ? 100 : $pageSize;
        $sort = request()->param('sort', 1);
        $where = [];
        $where['status'] = 1;
        //type：1为商家活动商品；2为巨量百应爆品；3为精选推荐；4为9.9元
        if($type > 1 && $type <4){
            $where['goods_type'] = $type;
        }
        if($type == 4){
            $where['product_price'] = 990;
        }

        if($cid >0){
            $cidStr = CategoryModel::getCategoryIds($cid);
            if($cidStr != ''){
                $cids = explode(',', $cidStr);
            }else{
                $cids = [];
            }
            $cnames = $cids;
        }else if($cid == 0){
            $sql = "select cid from category";
            $ids = Db::query($sql);

            $cnames = array_reduce($ids, function ($result, $value) {
                return array_merge($result, array_values($value));
            }, array());
        }else if($cid == '-1'){
            //todo 7天热推款
            $sortStr='hot_promotion_wiseman desc';

            $sql = "select cid from category";
            $ids = Db::query($sql);

            $cnames = array_reduce($ids, function ($result, $value) {
                return array_merge($result, array_values($value));
            }, array());
        }
        $where2 =[];
        if($name != ''){
            $where2[] = ['product_name', 'like', '%'.$name.'%'];
        }
        $where3 = '';
        if($id != ''){
            $where3 = 'shop_ids="'.$id.'"';
        }
        $sortStr='order_count desc';
        switch ($sort){
            case 1://销量 倒序
                $sortStr='order_count desc';
                break;
            case 2://销量 升序
                $sortStr='order_count asc';
                break;
            case 3://售价 倒序
                $sortStr='product_price desc';
                break;
            case 4://售价 升序
                $sortStr='product_price asc';
                break;
            case 5://佣金率 升序
                $sortStr='commission_rate asc';
                break;
            case 6://佣金率 倒序
                $sortStr='commission_rate desc';
                break;
            case 7://佣金金额 升序
                $sortStr='commission asc';
                break;
            case 8://佣金金额  倒序
                $sortStr='commission desc';
                break;
        }

        $goods = ActivityGoods::field('id,apply_id,shop_ids,volume,order_count,pv_count,commission,buyin_activity_id,hot_promotion_wiseman,apply_id,product_id,product_promotion_id,product_name,product_price,product_img,product_stock,shop_name,shop_id,dsr,shop_phone,is_new,commission_effect_start_time,commission_effect_end_time,commission_rate,common_commission_rate,service_rate,promotion_url,promotion_price,promotion_stock,gift_info,promotion_step,audit_status,mini_show,create_time,update_time,category_id,goods_type')
            ->where(['audit_status'=>1,'mini_show'=>1])
            ->where($where)
            ->where($where2)
            ->where($where3)
            ->where('shop_ids != ""')
            ->where('category_id', 'IN', $cnames)
            ->order($sortStr)
            ->paginate(['page'=>$currentPage,'list_rows'=>$perPage]);

        if($goods){
            $goods = $goods->toArray();
            if($goods['data']){
                foreach($goods['data'] as $k=>$v){
                    $goods['data'][$k]['choose'] = 0;
                    if($share){
                        $name = '/static/product/goods_'.$k.'.jpg';
                        $filename = $_SERVER['DOCUMENT_ROOT'] .$name;
                        dlfile($v['product_img'],$filename);
                        $goods['data'][$k]['product_img'] = 'https://'.$_SERVER['SERVER_NAME']. $name;
                        $goods['data'][$k]['sg'] = round($v['product_price'] * $v['common_commission_rate'] / 100,2);
                    }
                }
            }

        }

        return $this->apiJson(1, 'ok', $goods);
    }

    /**
     * 方告位
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function ad(){
        $ads = Carouse::field('id,img,url,desc')->where('status',1)->select();
        $img = [];
        if($ads){
            $ads = $ads->toArray();
            foreach ($ads as $k=>$v){
                $item = ['id'=>$v['id'], 'image'=>$v['img'], 'title' => $v['desc']];
                $img[] = $item;
            }
        }
        return $this->apiJson(1, 'ok', $img);
    }

    /**
     * 我的选品库
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function choose_goods(){
        $currentPage = request()->param('current_page', 1);
        $pageSize = request()->param('per_page', 10);
        $perPage = $pageSize > 100 ? 100 : $pageSize;
        $chooses = ChooseGoods::goods($currentPage,$perPage);

        $chooses = $chooses? $chooses : [];

        if($chooses){
            if($chooses['data']){
                foreach($chooses['data'] as $k=>$v){
                    $chooses['data'][$k]['choose'] = 0;
                }
            }

        }

        return $this->apiJson(1, 'ok', $chooses);
    }

    /**
     * 添加商品到我的选品库
     * @return \think\response\Json
     */
    public function add_choose(){
        $gid = request()->param('id', '');
        if($gid==''){
            return $this->apiJson(-1, '缺少参数');
        }

        $gids = explode(',', $gid);

        $res = ChooseGoods::choose($gids);

        if($res){
            return $this->apiJson(1, '添加成功');
        }else{
            return $this->apiJson(-1, '添加失败');
        }
    }

    /**
     * 删除商品库中商品
     * @return \think\response\Json
     */
    public function del_choose(){
        $gid = request()->param('id', '');
        if($gid == ''){
            return $this->apiJson(-1, '缺少参数');
        }

        $gids = explode(',', $gid);

        $res = ChooseGoods::delChoose($gids);

        if($res){
            return $this->apiJson(1, '删除成功');
        }else{
            return $this->apiJson(-1, '删除失败');
        }
    }

    /**
     * 商品详情
     * @return \think\response\Json
     */
    public function detail(){
        $id = request()->param('id', 0);
        if(!$id){
            return $this->apiJson(-1, '缺少参数');
        }
        $res = ActivityGoods::getDetail($id);
        $data = $res ? $res : [];
        return $this->apiJson(1, 'ok', $data);
    }

    /**
     * 收藏商品
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add_collection(){
        $id = request()->param('id', 0);
        if(!$id) return $this->apiJson(-1, '参数出错!');
        $g = ActivityGoods::find($id);
        if(!$g) return $this->apiJson(-1, '不存在此商品!');
        $uid = getUid();
        $res = UserCollection::where(['user_id'=>$uid, 'activity_goods_id'=>$id])->find();
        if($res) return $this->apiJson(-1, '已收藏!');
        $data = [
            'user_id' => $uid,
            'activity_goods_id' => $id,
            'create_time' => time(),
            'update_time' => time(),
        ];
        $result = UserCollection::insert($data);
        if($result){
            return $this->apiJson(1, '收藏成功!');
        }else{
            return $this->apiJson(-1, '收藏失败!');
        }
    }

    /**
     * 删除收藏
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function del_collection(){
        $id = request()->param('id', 0);
        if(!$id) return $this->apiJson(-1, '参数出错!');
        $g = ActivityGoods::find($id);
        if(!$g) return $this->apiJson(-1, '不存在此商品!');
        $uid = getUid();
        $res = UserCollection::where(['user_id'=>$uid, 'activity_goods_id'=>$id])->find();
        if($res){
            $result = $res->delete();
            if($result){
                return $this->apiJson(1, '取消收藏!');
            }else{
                return $this->apiJson(-1, '取消收藏失败!');
            }
        }else{
            return $this->apiJson(-1, '取消收藏失败!');
        }
    }

    /**
     * 用户收藏列表
     * @return \think\response\Json
     */
    public function collection(){
        $currentPage = request()->param('current_page', 1);
        $pageSize = request()->param('per_page', 10);
        $perPage = $pageSize > 100 ? 100 : $pageSize;
        $goods = UserCollection::getGoods($currentPage,$perPage);
        return $this->apiJson(1, 'ok', $goods);
    }

    /**
     * 关联主播、关联直播
     * @return \think\response\Json
     */
    public function getProductInfo(){
        $type = request()->param('type', 1);
        $pid = request()->param('pid', 0);
        $currentPage = request()->param('current_page', 1);
        $pageSize = request()->param('per_page', 10);
        $perPage = $pageSize > 100 ? 100 : $pageSize;

        if(!$type || !$pid){
            return $this->apiJson(-1, '缺少参数!');
        }
        $data = GoodsAuthor::getLiveAnchor($pid, $type, $currentPage, $perPage);
        return $this->apiJson(1, 'ok', $data);
    }

    /**
     * 达人带货的商品
     * @return \think\response\Json
     */
    public function getWismanGoods(){
        $author_id = request()->param('id', '');
        $currentPage = request()->param('current_page', 1);
        $pageSize = request()->param('per_page', 10);
        $perPage = $pageSize > 100 ? 100 : $pageSize;
        if($author_id ==''){
            return $this->apiJson(-1, '缺少参数!');
        }
        $goods = WisemanGoods::goods($author_id, $currentPage, $perPage);
        return $this->apiJson(1, 'ok', $goods);
    }
}